package com.example.smart.controller;

import com.example.common.util.R;
import com.example.smart.pojo.Role;
import com.example.smart.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/role/")
@Tag(name = "显示角色数据")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @PreAuthorize("hasAuthority('role:list')")
    @Operation(summary = "获得所有的角色数据")
    @GetMapping(value = "/getAllRole")
    public R getAllRole() {
        List< Role > roleList = roleService.list();
        return R.ok("查询所有角色数据成功").data("roleList", roleList);
    }

    @PreAuthorize("hasAuthority('role:add')")
    @Operation(summary = "增加角色")
    @PostMapping(value = "/addRole")
    public R addRole(@RequestBody Role role) {
        boolean flag = roleService.save(role);
        if (flag) {
            return R.ok("角色增加成功");
        } else {
            return R.error("角色增加失败");
        }
    }

    @PreAuthorize("hasAuthority('role:delete')")
    @Operation(summary = "删除角色")
    @DeleteMapping(value = "/deleteRole/{roleId}")
    public R deleteRole(@PathVariable("roleId") Integer roleId) {
        boolean flag = roleService.removeById(roleId);
        if (flag) {
            return R.ok("角色删除成功");
        } else {
            return R.error("角色删除失败");
        }
    }

    @PreAuthorize("hasAuthority('role:update')")
    @Operation(summary = "按照角色编号查询数据")
    @GetMapping(value = "/getRoleById/{roleId}")
    public R getByIdRole(@PathVariable("roleId") Integer roleId) {
        Role role = roleService.getById(roleId);
        return R.ok("按照角色编号查询数据成功").data("role", role);
    }

    @PreAuthorize("hasAuthority('role:update')")
    @Operation(summary = "修改角色")
    @PutMapping(value = "/updateRole")
    public R updateRole(@RequestBody Role role) {
        boolean flag = roleService.updateById(role);
        if (flag) {
            return R.ok("角色修改成功");
        } else {
            return R.error("角色修改失败");
        }
    }
}
